from PySide6.QtCore import Qt, Signal, QSize
from PySide6.QtWidgets import  QWidget
from PySide6.QtGui import QPixmap, QBitmap, QPainter, QImage
import cv2


class Tab1widget(QWidget):
    passurl = Signal(str)
    preview = Signal(str, QSize)
    def  __init__(self, parent=None):
        super().__init__(parent)
        self.pixpic = QPixmap()
        self.bitmap = QBitmap()
        self.blackpoint = "■■■"
        self.blank = "   "
        self.ra = 0.1
        self.blocksz = 13
    
    def cvop(self, cvimg):
        hei, wid = cvimg.shape[:2]
        wd = int(wid * self.ra)
        hi = int(hei * self.ra)
        afrcps = cv2.resize(cvimg, (wd, hi))
        grayimg =  cv2.cvtColor(afrcps, cv2.COLOR_BGR2GRAY)
        adpthreshld = cv2.adaptiveThreshold(grayimg,
                                            255,
                                            cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                                            cv2.THRESH_BINARY,
                                        self.blocksz, 1)
        return adpthreshld
    
        
    def cv2op(self, cvimg):
        adpthreshld = self.cvop(cvimg)
        # cv2.imshow("adpthreshld", adpthreshld)
        hei, wid = adpthreshld.shape[:2]
        print(f"number of all points is {3 * wid} * {hei}")
        sr = ''
        for i in range(hei):
            for j in range(wid):
                pixvalue = adpthreshld[i, j]
                if pixvalue == 0:
                    sr += self.blackpoint
                else:
                    sr += self.blank
            sr += '\n'
        sz = QSize(wid, hei)
        self.preview.emit(sr, sz)
        # cv2.waitKey(0)

                
    def paintEvent(self, event):
        if self.pixpic.isNull():
            return
        else:
            painter = QPainter(self)
            sz = self.size()
            pix = self.pixpic.scaled(sz.width(), sz.height(), Qt.KeepAspectRatio,
                        Qt.SmoothTransformation)
            painter.drawImage(0, 0, pix)
            painter.end()